package com.example.musicgui.client;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class UploadClient {
    private Socket socket = null;
    public UploadClient() throws IOException {
        socket = new Socket(Client.HOST,Client.PORT_THREE);
    }
    public void uploadFile(String url){
        try {
            // 获取文件名
            File file = new File(url);
            String fileName = file.getName();
            // 获取文件大小
            long fileSize = file.length();
            // 创建输出流
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            // 发送文件名和文件大小
            dos.writeUTF(fileName);
            dos.writeLong(fileSize);
            // 发送文件内容
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
            }

            System.out.println("音乐上传完成");
            fis.close();
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
